package cn.toleo.item.listener;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import cn.toleo.item.pojo.Item;
import cn.toleo.pojo.TbItem;
import cn.toleo.pojo.TbItemDesc;
import cn.toleo.service.ItemService;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class ItemAddMessageListener implements MessageListener{
	@Autowired
	private ItemService itemService;
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@Value("${HTML_OUT_PATH}")
	private String HTML_OUT_PATH;

	@Override
	public void onMessage(Message message) {
	try{
		//主干基础连环
		TextMessage textMessage=(TextMessage)message;
		String strId = textMessage.getText();
		long itemId = Long.parseLong(strId);
		//等待事务提交很重要
		Thread.sleep(1000);
		TbItem tbItem = itemService.getItemById(itemId);
		TbItemDesc itemDesc = itemService.geTbItemDescById(itemId);
		Item item = new Item(tbItem);
		
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate("item.ftl");
		
		Map data = new HashMap<>();
		data.put("item", item);
		data.put("itemDesc", itemDesc);
		
		//主干
		Writer out = new FileWriter(new File(HTML_OUT_PATH + strId +".html"));
		
		//结果,生成静态页面
		template.process(data,out);
		//结果修饰
		out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
